package com.demo.webapp.jcaptcha.security.authentication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.demo.security.core.SecurityMessageSource;
import com.demo.webapp.jcaptcha.core.PluginConstants;

/**
 * 对验证码进行验证的安全框架
 * 
 * @author ryuu.kk
 */
public class CaptchaAndUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
	
	protected MessageSourceAccessor messages = SecurityMessageSource.getAccessor();
	
    private boolean postOnly = true;

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String username = obtainUsername(request);
        String password = obtainPassword(request);

        String captcha = obtainCaptcha(request);
        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();
        String sessionId = request.getSession().getId();
        CaptchaAndUsernamePasswordAuthenticationToken authRequest = new CaptchaAndUsernamePasswordAuthenticationToken(username, password, captcha, sessionId);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }
    
	@Override
	public void setMessageSource(MessageSource messageSource) {
		this.messages = new MessageSourceAccessor(messageSource);
	}
	
    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
        super.setPostOnly(postOnly);
    }
    
    protected String obtainCaptcha(HttpServletRequest request) {
        return request.getParameter(PluginConstants.J_CAPTCHA_RESPONSE);
    }
}
